//
//  CJTemplateContainerBaseView.m
//  TSDemo_ImageFilter
//
//  Created by qian on 2014/5/8.
//  Copyright (c) 2014年 dvlproad. All rights reserved.
//

#import "CJTemplateContainerBaseView.h"

static CGFloat kDuration = 0.2;

@interface CJTemplateContainerBaseView () {
    BOOL contain;
    CGPoint startPoint;
    CGPoint originPoint;
}
@property (nonatomic, assign, readonly) BOOL allowExchange;     /**< 是否允许交换 */
@property (nonatomic, copy, readonly) void(^templateExchangeCompleteBlock)(void);   /**< 交换结束的回调 */


@property (nonatomic, strong) CJTemplateBaseView *firstView;
@property (nonatomic, strong) CJTemplateBaseView *secondView;
@property (nonatomic, strong) CJTemplateBaseView *thirdView;
@property (nonatomic, strong) CJTemplateBaseView *fourthView;
@property (nonatomic, strong) CJTemplateBaseView *fifthView;
@property (nonatomic, strong) CJTemplateBaseView *tempView; //交换时的中间变量

@end


@implementation CJTemplateContainerBaseView

- (void)dealloc {
    [_contentViewArray removeAllObjects];
    _contentViewArray = nil;
    _dataModels = nil;
    
    [self releaseTemplateView:_firstView];
    [self releaseTemplateView:_secondView];
    [self releaseTemplateView:_thirdView];
    [self releaseTemplateView:_fourthView];
    [self releaseTemplateView:_fifthView];
    
    _tempView = nil;
}

/*
 *  释放资源
 *
 *  @param templateView     模板视图
 */
- (void)releaseTemplateView:(UIView *)templateView {
    [templateView removeFromSuperview];
    templateView = nil;
}


#pragma mark - Init
/*
 *  初始化
 *
 *  @param frame frame
 *  @param templateCreateBlock              模板上子视图的创建方法
 *  @param templateDataConfigBlock          模板上数据的设置方法
 *  @param allowExchange                    是否允许交换
 *  @param templateExchangeCompleteBlock    交换结束的回调
 *
 *  @return 模板整体视图
 */
- (instancetype)initWithFrame:(CGRect)frame
          templateCreateBlock:(CJTemplateBaseView *(^ _Nonnull)(NSInteger templateIndex))templateCreateBlock
      templateDataConfigBlock:(void(^ _Nullable)(CJTemplateBaseView *bTemplateView, id bDataModel, CJTemplateDataConfigTime time, NSInteger templateIndex))templateDataConfigBlock
                allowExchange:(BOOL)allowExchange
        exchangeCompleteBlock:(void(^ _Nullable)(void))templateExchangeCompleteBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _templateDataConfigBlock = templateDataConfigBlock;
        
        _allowExchange = allowExchange;
        _templateExchangeCompleteBlock = templateExchangeCompleteBlock;
        
        [self setupViewsWithTemplateCreateBlock:templateCreateBlock];
    }
    return self;
}

- (void)setupViewsWithTemplateCreateBlock:(CJTemplateBaseView *(^)(NSInteger templateIndex))templateCreateBlock {
    self.backgroundColor = [UIColor whiteColor];
    
//    _firstView = [[CJTemplateBaseView alloc] initWithFrame:CGRectZero];
//    _secondView = [[CJTemplateBaseView alloc] initWithFrame:CGRectZero];
//    _thirdView = [[CJTemplateBaseView alloc] initWithFrame:CGRectZero];
//    _fourthView = [[CJTemplateBaseView alloc] initWithFrame:CGRectZero];
//    _fifthView = [[CJTemplateBaseView alloc] initWithFrame:CGRectZero];
    
    if (templateCreateBlock) {
        _firstView = templateCreateBlock(0);
        _secondView = templateCreateBlock(1);
        _thirdView = templateCreateBlock(2);
        _fourthView = templateCreateBlock(3);
        _fifthView = templateCreateBlock(4);
    }
    _firstView.tag = 1;
    _secondView.tag = 2;
    _thirdView.tag = 3;
    _fourthView.tag = 4;
    _fifthView.tag = 5;
    
    [self resetAllView];
    
    if (_contentViewArray == nil) {
        _contentViewArray = [NSMutableArray arrayWithCapacity:5];
    }
    
    [_contentViewArray addObject:_firstView];
    [_contentViewArray addObject:_secondView];
    [_contentViewArray addObject:_thirdView];
    [_contentViewArray addObject:_fourthView];
    [_contentViewArray addObject:_fifthView];
    
    
    [self addSubview:_firstView];
    [self addSubview:_secondView];
    [self addSubview:_thirdView];
    [self addSubview:_fourthView];
    [self addSubview:_fifthView];
    
}

#pragma mark - Reset:重置
/**
 *  设置所有的样式
 */
- (void)resetAllView {
    [self styleSettingWithTemplateView:_firstView templateIndex:0];
    [self styleSettingWithTemplateView:_secondView templateIndex:1];
    [self styleSettingWithTemplateView:_thirdView templateIndex:2];
    [self styleSettingWithTemplateView:_fourthView templateIndex:3];
    [self styleSettingWithTemplateView:_fifthView templateIndex:4];

}

/**
 *  设置样式
 */
- (void)styleSettingWithTemplateView:(CJTemplateBaseView *)templateView templateIndex:(NSInteger)templateIndex
{
    templateView.frame = CGRectZero;
    [templateView setClipsToBounds:YES];
    
    if (self.templateDataConfigBlock) {
        self.templateDataConfigBlock(templateView, nil, CJTemplateDataConfigTimeReset, templateIndex);
    } else {
//        [view setImageViewData:nil];
    }
    
    
    templateView.realTemplateModel = nil;
    [templateView setUserInteractionEnabled:YES];
    
    if (self.allowExchange) {
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
        [templateView addGestureRecognizer:longGesture];
    }
}


#pragma mark - Update：更新样式
/*
 *  完善模型样式在真正坐标系下的真实信息
 *
 *  @param realTemplateModels               真正的模板模型信息
 *  @param realPointBorderLayerCreateBlock  真正的模板模型信息的边框layer创建(此属性为nil时候表示不设置边框)
                                            (创建layer时候不用提供path和frame,内部会自动补充)
 */
- (void)improveTemplateWithRealTemplateModels:(NSArray<CJTemplatePositionModel *> *)realTemplateModels
              realPointBorderLayerCreateBlock:(CAShapeLayer *(^ _Nullable)(void))realPointBorderLayerCreateBlock
{
    self.realTemplateModel.realTemplateModels = realTemplateModels;
    
    if (realTemplateModels.count == 0) {
        return;
    }
    
    // 先重置所有，再分别设置对应
    [self resetAllView];
    NSInteger templateCount = realTemplateModels.count;
    for (NSInteger templateIndex = 0; templateIndex < templateCount; templateIndex++) {
        CJTemplatePositionModel *realTemplateModel = realTemplateModels[templateIndex];
        
        if (templateIndex < [self.contentViewArray count]) {
            CGRect templateCellFrame = realTemplateModel.realSubFrame;
             
            // 1、获取视图
            CJTemplateBaseView *imageView = (CJTemplateBaseView *)[self.contentViewArray objectAtIndex:templateIndex];
            imageView.frame = templateCellFrame;
            imageView.realTemplateModel = realTemplateModel;
            
            // 2、为视图添加曲线路径(方法1和方法2，只能取一种。推荐方法2)
            // 方法1(常见)：在具体的view上设置layer
            //[imageView setNeedsDisplay]; // 会调用drawRect方法
            
            // 方法2（本例中推荐）：在本.m中直接设置layer
            CGRect templateCellBounds = CGRectMake(0, 0, CGRectGetWidth(templateCellFrame), CGRectGetHeight(templateCellFrame));
            CAShapeLayer *realPointMaskLayer = [CAShapeLayer layer];
            realPointMaskLayer.path = [realTemplateModel.realTemplatePointPath CGPath];
            realPointMaskLayer.fillColor = [[UIColor whiteColor] CGColor];
            realPointMaskLayer.frame = templateCellBounds;
            imageView.layer.mask = realPointMaskLayer;
            
            // 3、为视图添加边框
            if (realPointBorderLayerCreateBlock != nil) {
                if (imageView.realPointBorderLayer == nil) {
                    CAShapeLayer *realPointBorderLayer = realPointBorderLayerCreateBlock();
                    //CAShapeLayer *realPointBorderLayer = [CAShapeLayer layer];
                    //realPointBorderLayer.fillColor = UIColor.clearColor.CGColor; // 必须透明
                    //realPointBorderLayer.strokeColor = UIColor.greenColor.CGColor;
                    //realPointBorderLayer.lineWidth = 5;
                    [imageView.layer addSublayer:realPointBorderLayer];
                    imageView.realPointBorderLayer = realPointBorderLayer;
                }
                
                //UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:templateCellBounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:(CGSizeMake(40, 40))];
                UIBezierPath *path = realTemplateModel.realTemplatePointPath;
                imageView.realPointBorderLayer.path = [path CGPath];
                imageView.realPointBorderLayer.frame = templateCellBounds;
            }
        }
    }
}


#pragma mark - Update：更新数据
/*
 *  设置/更新模板快里的数据（不会改变整个模板的形状）
 *
 *  @param dataModels   模板快里的数据
 */
- (void)reloadTemplateCellWithDataModels:(NSArray *)dataModels {
    _dataModels = dataModels;
    
    NSInteger templateCount = self.cellCount;
    templateCount = dataModels.count;       // TODO:后续待完善cellCount
    if (dataModels.count != templateCount) {
        NSLog(@"警告⚠️⚠️⚠️⚠️⚠️：设置的数据个数和模板的模块个数不一致");
    }
    
    // 为视图设置显示数据
    for (NSInteger templateIndex = 0; templateIndex < templateCount; templateIndex++) {
        if (templateIndex < [self.contentViewArray count]) {
            id imageModel = [self.dataModels objectAtIndex:templateIndex]; // 目前imageModel可能为 UIImage 或 Url
            
            CJTemplateBaseView *imageView = (CJTemplateBaseView *)[self.contentViewArray objectAtIndex:templateIndex];
            if (self.templateDataConfigBlock) {
                self.templateDataConfigBlock(imageView, imageModel, CJTemplateDataConfigTimeCreate, templateIndex);
            }
        }
    }
}


#pragma mark - 长按换位的功能
//长按换位的功能
- (void)buttonLongPressed:(UILongPressGestureRecognizer *)sender
{
    UIView *templateView = (CJTemplateBaseView *)sender.view;
    //NSLog(@"templateView.tag::%d", templateView.tag);
    if (sender.state == UIGestureRecognizerStateBegan)
    {
        startPoint = [sender locationInView:sender.view];
        originPoint = templateView.center;
        [self bringSubviewToFront:templateView];
        [UIView animateWithDuration:kDuration animations:^{
            
            templateView.transform = CGAffineTransformMakeScale(1.1, 1.1);
            templateView.alpha = 0.7;
        }];
    }
    else if (sender.state == UIGestureRecognizerStateChanged)
    {
        CGPoint newPoint = [sender locationInView:sender.view];
        CGFloat deltaX = newPoint.x-startPoint.x;
        CGFloat deltaY = newPoint.y-startPoint.y;
        templateView.center = CGPointMake(templateView.center.x+deltaX,templateView.center.y+deltaY);
        //NSLog(@"center = %@",NSStringFromCGPoint(templateView.center));
        NSInteger index = [self indexOfPoint:templateView.center withButton:templateView];
        NSLog(@"===%d",index);
        
        if (index<0)
        {
            contain = NO;
            _tempView = nil;
        }
        else
        {
            if (index != -1) {
                _tempView = _contentViewArray[index];
            }

            [UIView animateWithDuration:kDuration animations:^{
                
//                CGPoint temp = CGPointZero;
//                CJTemplateBaseView *button = _contentViewArray[index];
//                temp = button.center;
//                button.center = originPoint;
//                templateView.center = temp;
//                originPoint = templateView.center;
//                contain = YES;
            }];
        }
        
        
    }
    else if (sender.state == UIGestureRecognizerStateEnded)
    {
        [UIView animateWithDuration:0.2 animations:^{
            
            templateView.transform = CGAffineTransformIdentity;
            templateView.alpha = 1.0;
            if (!contain)
            {
//                templateView.center = originPoint;
                if (_tempView) {
                    [self exchangeFromIndex:templateView.tag-1 toIndex:_tempView.tag-1];
                }else{
                
                    [templateView setFrame:templateView.frame];
                }
            }
            _tempView = nil;
        }];
    }
}


/*
 *  交换模板
 *
 *  @param fIndex   操作的template的Index
 *  @param toIndex  和哪一个交换
 */
- (void)exchangeFromIndex:(NSInteger)fIndex toIndex:(NSInteger)toIndex
{
    id fromDataModel = [_dataModels objectAtIndex:fIndex];
    id toDataModel = [_dataModels objectAtIndex:toIndex];
    
    [_dataModels replaceObjectAtIndex:fIndex withObject:toDataModel];
    [_dataModels replaceObjectAtIndex:toIndex withObject:fromDataModel];
    
    CJTemplateBaseView *fromView = [_contentViewArray objectAtIndex:fIndex];
    CJTemplateBaseView *toView = [_contentViewArray objectAtIndex:toIndex];
    
    [_contentViewArray replaceObjectAtIndex:fIndex withObject:toView];
    [_contentViewArray replaceObjectAtIndex:toIndex withObject:fromView];

    
    CJTemplatePositionModel *fromViewRealTemplateModel = fromView.realTemplateModel;
    NSInteger fromViewTag = fromView.tag;
    
    CJTemplatePositionModel *toViewRealTemplateModel = toView.realTemplateModel;
    NSInteger toViewTag = toView.tag;
    
    fromView.tag = toViewTag;
    fromView.realTemplateModel = toViewRealTemplateModel;
    fromView.frame = toViewRealTemplateModel.realSubFrame;
    
    toView.tag = fromViewTag;
    toView.realTemplateModel = fromViewRealTemplateModel;
    toView.frame = fromViewRealTemplateModel.realSubFrame;
    

    if (self.templateDataConfigBlock) {
        self.templateDataConfigBlock(fromView, fromDataModel, CJTemplateDataConfigTimeExchange, fIndex);
        self.templateDataConfigBlock(toView, toDataModel, CJTemplateDataConfigTimeExchange, toIndex);
    }
    
    !self.templateExchangeCompleteBlock ?: self.templateExchangeCompleteBlock();
}



- (NSInteger)indexOfPoint:(CGPoint)point withButton:(UIView *)templateView
{
    for (NSInteger i = 0; i<_contentViewArray.count; i++) {
        UIView *iTemplateView = _contentViewArray[i];
        if (iTemplateView != templateView) {
            if (CGRectContainsPoint(iTemplateView.frame, point)) {
                return i;
            }
        }
    }
    return -1;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
